package encryption;

import org.junit.Test;
import sun.misc.BASE64Encoder;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

/**
 * @author
 * @Title: CodeTest
 * @Description:
 * @date 2022/4/13 6:00 下午
 * 公钥和私钥生成工具类
 */
public class PublicAndPrivateKeyGenerate {
    /**
     * 指定加密算法为RSA
     */
    private static final String ALGORITHM = "RSA";
    /**
     * 密钥长度，用来初始化
     */
    private static final int KEYSIZE = 1024;

    /**
     * 生成公钥与私钥对,每次生成的秘钥都是不同的!!!
     *
     * @return 公钥Key=publicKey 私钥Key=privateKey
     * @throws Exception
     */
    @Test
    public void generateKeyPair() throws Exception {

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);

        keyPairGenerator.initialize(KEYSIZE);

        /** 生成密匙对 */
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        /** 得到公钥 */
        Key publicKey = keyPair.getPublic();

        /** 得到私钥 */
        Key privateKey = keyPair.getPrivate();

        /**
         *
         * MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMu69eAlFpdEgDCaR1nPgjH8jbAgioua5xZYn4
         * S9kFi+vhM98cbEWfH8aRcV0rDglpPsIwcx+ycqRNKjIdtlAAkWnabIrmBDrrOZQTMpgAcA4F5A0R
         * kEgm4WUKAeIEnHrQcASmrL6I+TwS41iQx7jXwhA9lWztlXXSQgp37m6I+wIDAQAB
         *
         *
         * MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIy7r14CUWl0SAMJpHWc+CMfyNsC
         * CKi5rnFlifhL2QWL6+Ez3xxsRZ8fxpFxXSsOCWk+wjBzH7JypE0qMh22UACRadpsiuYEOus5lBMy
         * mABwDgXkDRGQSCbhZQoB4gScetBwBKasvoj5PBLjWJDHuNfCED2VbO2VddJCCnfuboj7AgMBAAEC
         * gYBypY82aXMDEox7lQZaHfbzPjh1WdHOCf33OP3NvZRddWBChOxUDkwlVlCAObbplTTLfSnbKF4B
         * FG2OwzoyhEvk+uEJFip2Re1DoYOj0YHjdSN7OdEbj974jFs0mVAABhW5DsKYXq2OthVcc/5yqLpp
         * iaj8SetvZ4mu7Qowc3diuQJBAPXsP9ZjqNkhbbvSg5bN9XAJ57S9GWxouSeNfm+JzIGRnRRygj5U
         * pOCbo9qlHoyUMoZm8975WN0i2A0tmV+urY8CQQCSf/y0n3KGc4Sy/SRZPatuTlou44nLAmWBeSMC
         * bzC8HDzkg0b2qydgYinRCBMixk6zxMN1RQeR4xRCT+sKZ0/VAkEAh904u4odq6/jPyQjnPo2geqG
         * /3yFgjYtLOPoGVkpCeBXxwcoW6VJ3ek+0jntMb9iVoykaOibJrjsYgNyO8F2kwJAbQ6v/XoRFHvc
         * Vi5SJ8jb3HKhefRS+HhhPgACiuZhHjfbMLV1V11UI9EPlhdvv1xm7DZW1u67UuP7id3ad9UuvQJA
         * XZ46+wZsHrVr9VbhQdmqzfkP7rSdosQr5GDV8WXVL2HA/nBj4mnQoCbWIcyKBOCBcFyZK20zQvOm
         * /66n7z/zKA==
         *
         *
         *
         *
         *
         */

        String publicKeyStr = new BASE64Encoder().encode(publicKey.getEncoded());
        String privateKeyStr = new BASE64Encoder().encode(privateKey.getEncoded());
        System.out.println("pub:" + publicKeyStr);
        System.out.println("pri:" + privateKeyStr);
    }







}
